/**
 *  创建模块
 *  @author yangzc
 */
var app = {
    util:{}
};
//工具方法模块
app.util = {
    $ : function (selector, node) {
        return (node || document).querySelector(selector);
    },
    formateTime:function (ms) {
        var d = new Date(ms);
        var pad = function (s) {
            if(s.length<1){
                s = '0'+s;
            }
            return s;
        }
        var year = d.getFullYear()
        var month = d.getMonth()+1;
        var date = d.getDate();
        var hour = d.getHours();
        var minute = d.getMinutes();
        var second = d.getSeconds();
        return year + '-' + pad(month) + '-' + pad(date) + ' ' + pad(hour) + ':' + pad(minute) + ':' + pad(second);
    }
};

app.store = {
    __store_key : '__sticky_note__',
    get : function (id) {
        var notes = this.getNotes();
        return notes[id] || {};
    },
    set : function (id,value) {
        var notes = this.getNotes();
        if(notes[id]){
            Object.assign(notes[id],value);
        }
        else{
            notes[id] = value;
        }
        localStorage[this.__store_key] = JSON.stringify(notes);
        console.log("save note id"+id+" content:"+JSON.stringify(value));
    },
    getNotes : function () {
        return JSON.parse(localStorage[this.__store_key] || '{}');
    }
};

(function(util,store) {
    var $ = util.$;
    var moveNote = null;
    var startX;
    var startY;
    var maxZIndex = 0;
    var noteTpl = '<div class="ui-model">\n' +
        '        <i class="ui-delete"><img class="ui-img" src="delete.png"></i>\n' +
        '        <div class="ui-textarea" contenteditable="true">\n' +
        '        </div>\n' +
        '        <div class="ui-foot">\n' +
        '            2018-01-24\n' +
        '        </div>\n' +
        '  </div>';

    function Note(options) {
        var note = document.createElement("div");
        note.className = "ui-model";
        note.id = options.id || "m-note-" + Date.now();
        note.innerHTML = noteTpl;
        $(".ui-textarea", note).innerHTML = options.content || "";
        note.style.left = options.left + "px";
        note.style.top = options.top + "px";
        note.style.zIndex = options.zIndex;
        document.body.appendChild(note);
        this.note = note;
        this.updateTime(options.updateTime);
        this.save();
        this.addEvent();
    }

    Note.prototype.close = function (e) {
        document.body.removeChild(this.note);
    }


    Note.prototype.addEvent = function () {
        //便签的mouseDown事件
        var mousedownHandle = function (e) {
            moveNote = this.note;
            startX = e.clientX - this.note.offsetLeft;
            startY = e.clientY - this.note.offsetTop;
            if (parseInt(this.note.style.zIndex) != maxZIndex - 1) {
                this.note.style.zIndex = maxZIndex++;
                store.set(this.note.id, {
                    zIndex: maxZIndex - 1
                });
            }
        }.bind(this);
        this.note.addEventListener("mousedown", mousedownHandle);


        //便签的输入事件
        var editior = $(".ui-textarea", this.note);
        var inputTimer;

        var inputHandler = function inputHandler(e) {
            var content = editior.innerHTML;
            clearTimeout(inputTimer);
            inputTimer = setTimeout(function () {
                var time = Date.now();
                store.set(this.note.id, {
                    content: content,
                    updateTime: time
                });
                this.updateTime(time);
            }.bind(this), 300);
        }.bind(this);

        editior.addEventListener("input",inputHandler);
        //关闭处理程序
        var closeBtn = $(".ui-delete", this.note);
        var closeHandle = function (e) {
            this.close(e);
            closeBtn.removeEventListener("click", closeHandle);
            this.note.removeEventListener("mouse", mousedownHandle)
        }.bind(this);
        closeBtn.addEventListener("click", closeHandle);
    }


    Note.prototype.updateTime = function (ms) {
        var ts = $(".ui-foot", this.note);
        ms = ms || Date.now();
        ts.innerHTML = util.formateTime(ms);
        this.updateTimeInMs = ms;
    }

    Note.prototype.save = function (e) {
        store.set(this.note.id, {
            left: this.note.offsetLeft,
            top: this.note.offsetTop,
            zIndex: parseInt(this.note.zIndex),
            content: $(".ui-textarea", this.note).innerHTML,
            updateTime: this.updateTimeInMs
        });
    }

    document.addEventListener("DOMContentLoaded", function (e) {
        $("#creatModel").addEventListener("click", function (e) {
            new Note({
                left: Math.round(Math.random() * (window.innerWidth - 200)),
                top: Math.round(Math.random() * (window.innerHeight - 200)),
                zIndex: maxZIndex++
            });
        })

        //移动监听
        function mousemoveHandle(e) {
            if (!moveNote) {
                return;
            }
            moveNote.style.left = e.clientX - startX + "px";
            moveNote.style.top = e.clientY - startY + "px";
        }

        function mouseupHandle(e) {
            if (!moveNote) {
                return;
            }
            store.set(moveNote.id, {
                left: moveNote.offsetLeft,
                top: moveNote.offsetTop,
            });
            moveNote = null;
        }

        document.addEventListener("mousemove", mousemoveHandle);
        document.addEventListener("mouseup", mouseupHandle);

        var notes = store.getNotes();
        Object.keys(notes).forEach(function (id) {
            var options = notes[id];
            if (maxZIndex < options.zIndex) {
                maxZIndex = options.zIndex;
            }
            new Note(Object.assign(options, {
                id: id
            }));
        });
        maxZIndex += 1;
    });
})(app.util,app.store);